<?php

namespace app\admin\controller;

use app\model\SiteSetting;
use support\Request;
use think\Exception;
use think\facade\Db;
use Webman\RedisQueue\Redis;
use \GatewayWorker\Lib\Gateway;

class CommonController extends BaseController
{

    /**
     * 上传图片文件
     * @params string
     * @return
     */
    public function uploadImage(Request $request)
    {
        return uploadFileCommon($request, 1);
    }

    /**
     * 大文件切片上传
     * @params string
     * @return
     */
    public function chunkUpload(Request $request)
    {

        $guid = $request->post('guid');
        $origin_file_name = $request->post('name');       //原始上传文件名称
        $total_chunks     = $request->post('chunks', 1);  //总文件切片数
        $now_chunk        = $request->post('chunk', 0);   //当前切片数
        $file_size        = $request->post('size');       //上文件大小kb
        $ext              = get_extension($origin_file_name);
        if(empty($guid) || empty($total_chunks)){
            return returnFail('上传文件无效');
        }
        //切片文件临时存储位置
        $saveSliceRootPath = public_path().'/upload/slicefile/'.$guid;
        $file = $request->file('file');
        $file->move($saveSliceRootPath.'/'.$now_chunk);
        $now_chunk+=1;
        if($now_chunk == $total_chunks){
            $mergeResult = $this->mergeSlice($saveSliceRootPath, $total_chunks, $ext);
            if (!$mergeResult) {
                return returnFail('上传失败');
            }else{
                $res['file_path'] = $mergeResult;
                $res['file_name'] = $origin_file_name;
                $res['size']      = sprintf("%.2f",substr(sprintf("%.3f", $file_size/1048576), 0, -1)).'MB';
                $res['time']      = date('Y-m-d H:i:s');
                return returnJson(100, '上传成功',$res);
            }
        }else{
            //return returnSuccess('正在上传第'.$now_chunk.'部分文件');
        }
    }

    /**
     * 合并切片文件
     * @params $slice_dir   切片文件路径
     * @params $total_chunks 总片数
     * @params $file_ext    文件后缀名
     * @return
     */
    public function mergeSlice($slice_dir, $total_chunks, $file_ext)
    {
        //上传配置
        $upload_setting = SiteSetting::getUploadSetting();
        //获取设置的本地存储位置
        $local_path = $upload_setting['path_info']['local'];
        if(empty($local_path['other_path']))
        {
            $local_path['other_path'] = '/upload/file/';
        }
        $return_local_path = $local_path['other_path'].date('Ymd');
        $save_local_path   = public_path().$return_local_path;
        //合并好的文件存储目录(需要移动到这里.)
        if(!is_dir($save_local_path)){
            @mkdir($save_local_path, 0777, true);
        }
        //重命名文件
        $temp_file_name = md5(get_random_str(6).getMillisecond());
        //新文件名称
        $new_file_name = $temp_file_name.'.'.$file_ext;
        //要移动到的路径
        $new_file_path = $save_local_path.'/'.$new_file_name;

        /******文件合并部分*******/
        $mergeFile = $slice_dir.'/'.$temp_file_name; //待合并的文件
        //文件不存在则创建之.
        if(!file_exists($mergeFile)){
            $temp_file = fopen($mergeFile, 'w+');
            fclose($temp_file);
        }
        $temp_file = fopen($mergeFile, 'a');

        //进行合并操作.
        for ($i = 0; $i <= $total_chunks-1; $i++) {
            // 单文件路径
            $filePart = $slice_dir.'/'.$i;
            if(file_exists($filePart)){
                $chunk = file_get_contents($filePart);
                // 写入chunk
                fwrite($temp_file, $chunk);
            }
        }
        fclose($temp_file);

        //重命名文件
        $renameResult = rename($mergeFile, $new_file_path);
        if($renameResult == false)
        {
            return false;
        }else{
            self::delDir($slice_dir);  //删除临时切片文件
            //判断设置的文件上传位置
            //上传文件三方存储的位置目前支持 阿里云 七牛云
            switch ($upload_setting['upload_path'])
            {
                case 'local':

                    $file_path = $local_path['local_domain'].$return_local_path.'/'.$new_file_name;
                    break;
                case 'ali':

                    $file_path = uploadAliOss($new_file_name, $new_file_path, $upload_setting['path_info'][$upload_setting['upload_path']]);
                    if(!$file_path)
                    {
                        return returnFail('阿里云上传文件失败');
                    }
                    break;
                case 'qn':
                    $file_path = uploadQnStore($new_file_name, $new_file_path, $upload_setting['path_info'][$upload_setting['upload_path']]);
                    if(!$file_path)
                    {
                        return returnFail('七牛云上传文件失败');
                    }
                    break;
                default:
                    $file_path = $local_path['local_domain'].$return_local_path.$new_file_name;
                    break;
            }
            //判断上传到三方存储是否删除本地文件
            if($upload_setting['upload_path'] != 'local')
            {
                if($upload_setting['delete_local'] == 1)
                {
                    deleteLocalFile($new_file_path);
                }
            }

            return $file_path;
        }

    }


    /**
     * 选择上传的图片
     * @params string
     * @return
     */
    public function selectImage(Request $request)
    {
        $type = $request->get('type');
        $admin_info = $request->admin_info;
        $where = [];
        if($admin_info['rules'] != '*')
        {
            $where['admin_id'] = $admin_info['id'];
        }
        $list_query = Db::name('upload_img')->where($where)->order('id','desc');
        if($type)
        {
            $list_query->where('type', $type);
        }
        $list = $list_query->paginate(14);
        $assign['list'] = $list;

        $def_upload_type[] = ['id'=>0, 'admin_id'=>1, 'name'=>'默认'];
        $upload_type = Db::name('upload_img_type')->where('admin_id', $admin_info['id'])->select()->toArray();
        if(empty($upload_type))
        {
            $new = $def_upload_type;
        }else{
            $new = array_merge($def_upload_type, $upload_type);
        }
        foreach ($new as $k=>$v)
        {
            $new[$k]['total'] = Db::name('upload_img')->where($where)->where('type', $v['id'])->count('id');
        }
        $assign['img_type'] = $new;

        return view('common/select_image', $assign);
    }

    /**
     * 删除图片存储
     * @params string
     * @return
     */
    public function delImage(Request $request)
    {
        try {
            $id = $request->post('id');
            $info = Db::name('upload_img')->where('id', $id)->find();
            Db::name('upload_img')->where('id', $id)->delete();
            $a = parse_url($info['file_path']);
            if(!empty($a) && !empty($a['path'])){
                $file_path = public_path().$a['path'];

                self::deleteLocalFile($file_path);
            }
            return returnSuccess('删除成功');
        }catch (Exception $e)
        {
            return returnFail('删除失败');
        }
    }

    /**
     * 删除本地文件
     * @params string
     * @return
     */
    public function deleteLocalFile($file_path)
    {
        if($file_path && file_exists($file_path))
        {
            @unlink($file_path);
        }
    }

    /**
     * 清除缓存
     * @params string
     * @return
     */
    public function cleanCache()
    {
        @@$this->delDir(runtime_path().'/views');
        @@$this->delDir(runtime_path().'/cache');
        return returnSuccess('清除缓存成功');
    }

    /**
     * 删除目录文件
     * @params string
     * @return
     */
    function delDir(string $path): bool
    {
        if (!is_dir($path)) {
            return false;
        }
        $open = opendir($path);
        if (!$open) {
            return false;
        }
        while (($v = readdir($open)) !== false) {
            if ('.' == $v || '..' == $v) {
                continue;
            }
            $item = $path . '/' . $v;
            if (is_file($item)) {
                unlink($item);
                continue;
            }
            self::delDir($item);
        }
        @@closedir($open);
        return rmdir($path);
    }

}
